//import Subscriber from '@ohos.commonevent';
import Subscriber from '@ohos.commonEvent';
import router from '@system.router';
import CheckEmptyUtils from '../../utils/CheckEmptyUtils.js';

let mCommonEventSubscriber = null;
let mCommonEventSubscribeInfo = {
    events: [Subscriber.Support.COMMON_EVENT_USB_DEVICE_DETACHED, Subscriber.Support.COMMON_EVENT_USB_DEVICE_ATTACHED,
    Subscriber.Support.COMMON_EVENT_USB_ACCESSORY_ATTACHED,
    Subscriber.Support.COMMON_EVENT_USB_ACCESSORY_DETACHED,
    Subscriber.Support.COMMON_EVENT_USB_STATE,]
};
let mIsSubscribed = false;

export default {
    data: {
        result: ''
    },
    onInit() {
        this.subUsbListener();
    },
    subUsbListener() {
        console.info("usb subUsbListener....");
        if (mIsSubscribed) {
            console.info("usb event already subscribed");
            this.result = "已经监听了...不要重复点击"
            return;
        }
        Subscriber.createSubscriber(mCommonEventSubscribeInfo, this.CreateSubscriberCallBack.bind(this));
    },
    CreateSubscriberCallBack(err, data) {
        this.result = "开始监听..."
        console.info("usb CreateSubscriberCallBack....");
        mCommonEventSubscriber = data;
        Subscriber.subscribe(mCommonEventSubscriber, this.SubscriberCallBack.bind(this));
        mIsSubscribed = true;
    },
    SubscriberCallBack(err, data) {
        this.result = "监听....回调"
        console.info("usb subscriber call back")

        // output result to page
        this.result = this.$t(JSON.stringify(data));
        console.info("usb=======================>SubscriberCallBack  data = " + JSON.stringify(data));
        console.info("usb=======================>SubscriberCallBack  event = " + data.event);
    },
    unSubscriberListener() {
        if (!mIsSubscribed || CheckEmptyUtils.isEmpty(mCommonEventSubscriber)) {
            console.info("usb event not subscribed");
            return;
        }
        this.result = "取消监听...."
        console.info("usb event unsubscribed");
        Subscriber.unsubscribe(mCommonEventSubscriber, () => {
            console.info("usb event unsubscribed");
        });
        mIsSubscribed = false;
    },
    onDestroy() {
        console.info("usb onDestroy");
        this.unSubscriberListener();
    },
    onBackPress() {
        router.back();
    },
}
